<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="form.categoryId !== 0" label="分类" prop="categoryId">
        <treeselect style="width: 200px" v-model="queryParams.categoryId" :options="categoryList" :normalizer="normalizer" placeholder="选择上级类型" />
      </el-form-item>
      <el-form-item label="类型状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择类型状态" clearable size="small">
          <el-option label="" value="" />
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否热门" prop="status">
        <el-select v-model="queryParams.isHot" placeholder="请选择是否热门" clearable size="small">
          <el-option label="" value="" />
          <el-option label="热门" value="1" />
          <el-option label="普通" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['blog:blog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:blog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:blog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['blog:blog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="文章标题" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span>{{getCategoryNameById(scope.row.categoryId,categoryList)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="introduction" />
      <el-table-column label="封面图片" align="center" prop="coverImgUrl">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.coverImgUrl"
            :fit="'contain'"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否热门" align="center" prop="isHot" />-->
      <el-table-column prop="status" label="是否热门" width="100">
        <template slot-scope="scope" >
          <el-tag type="danger" v-if="scope.row.isHot=='1'" >热门</el-tag>
          <el-tag  v-else >普通</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="likeCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['blog:blog:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改博客对话框 @opened="setEditorContent" -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div>
        <el-row :gutter="15">
          <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.categoryId !== 0">
              <el-form-item label="分类" prop="categoryId">
                <treeselect v-model="form.categoryId" :options="categoryList" :normalizer="normalizer" placeholder="选择上级类型" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="封面" prop="coverImgUrl">
                <image-upload :limit="1" ref="coverImg"  @input="setCoverImgUrl"></image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="简介" prop="introduction">
                <el-input v-model="form.introduction" type="textarea" placeholder="请输入简介"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否热门" prop="isHot" required>
                <el-switch v-model="form.isHot"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="作者" prop="createBy">
                <el-input v-model="form.createBy" placeholder="请输入作者" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="博客内容" prop="content">
                <editor-md ref="editorMd"></editor-md>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory,listBlog, getBlog, delBlog, addBlog, updateBlog,getContent } from "@/api/blog/blog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import editorMD from "../../../components/EditorMd/editorMD";
import EditorMd from "../../../components/EditorMd/editorMD";

export default {
  name: "Blog",
  dicts: ['sys_show_hide','sys_normal_disable'],
  components: {EditorMd, Treeselect,editorMD},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 博客表格数据
      blogList: [],
      //分类
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: true,
      //editormd内容
      editorContent: "",
      //是否Dialog加载
      createFlag: false,
      //isHot显示
      isHotShow:[{'value':0,'label':'普通'},{'value':1,'label':'热门'}],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        authorId: null,
        title: null,
        contentId: null,
        categoryId: null,
        introduction: null,
        coverImgUrl: null,
        status: null,
        isHot: null,
        likeCount: null,
      },
      //表单参数
      form: {
        title: undefined,
        categoryId: undefined,
        coverImgUrl: null,
        introduction: undefined,
        isHot: false,
        status: undefined,
        createBy: undefined,
        content: "",
        contentWrite: ""
      },
      //表单校验
      rules: {
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        categoryId: [{
          required: true,
          message: '请选择分类',
          trigger: 'change'
        }],
        introduction: [{
          required: true,
          message: '请输入简介',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          message: '是否可见不能为空',
          trigger: 'change'
        }],
        createBy: [{
          required: true,
          message: '请输入作者',
          trigger: 'blur'
        }],
        content: [{
          required: false,
          message: '请输入多行文本',
          trigger: 'blur'
        }],
      },
      coverImgUrlAction: process.env.VUE_APP_BASE_API + "/common/upload",
      coverImgUrlfileList: [],
      instance: null,
    };
  },
  created() {
    this.getList();
    this.open=false;
  },
  mounted() {
    // 将分享方法绑定在window上
    window['setEditorContent'] = () => {
      this.setEditorContent();
    }
  },
  methods: {
    /** 查询博客列表 */
    getList() {
      this.loading = true;
      listBlog(this.queryParams).then(response => {
        this.blogList = response.rows;
        this.total = response.total;
        this.getCategories();
      });
    },

    /** 查询分类列表 */
    getCategories() {
      listCategory().then(response => {
        this.categoryList = this.handleTree(response.rows, "categoryId");
        this.loading = false;
      });
    },
    /** 转换类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.text,
        children: node.children
      };
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        blogId: null,
        authorId: null,
        title: null,
        content: "",
        contentWrite: "",
        categoryId: null,
        introduction: null,
        coverImgUrl: [],
        status: "0",
        delFlag: null,
        isHot: null,
        createBy: null,
        likeCount: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.blogId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.$refs.editorMd.editorSetContent(this.editorContent);
      this.$refs.coverImg.setFileList(this.form.coverImgUrl);
      this.title = "添加博客";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const blogId = row.blogId || this.ids
      getBlog(blogId).then(response => {
        this.form = response.data;
        this.form.isHot = (this.form.isHot==="1");
        this.title = "修改博客";
        this.open = true;
        getContent(response.data.contentId).then(response => {
          this.form.content = response.data.content;
          this.editorContent = response.data.contentWrite;
          if(this.createFlag) {
            this.$refs.editorMd.editorSetContent(this.editorContent);
            this.$refs.coverImg.setFileList(this.form.coverImgUrl);
            this.setCoverImgUrl(this.form.coverImgUrl);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.content = this.$refs.editorMd.getEditorHtml();
      this.form.contentWrite = this.$refs.editorMd.getEditorContent();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.blogId != null) {
            updateBlog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBlog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const blogIds = row.blogId || this.ids;
      this.$modal.confirm('是否确认删除博客为"' + blogIds + '"的数据项？').then(function() {
        return delBlog(blogIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('blog/blog/export', {
        ...this.queryParams
      }, `blog_blog.xlsx`)
    },
    setCoverImgUrl(arg){
      let img = "";
      if(arg != null){
        img = arg.substring(arg.indexOf("/statics/") + 9);
      }
      this.form.coverImgUrl = img;
    },
    setEditorContent(){
      if(!this.createFlag){
        this.createFlag = true;
        this.$refs.editorMd.editorSetContent(this.editorContent);
        this.$refs.coverImg.setFileList(this.form.coverImgUrl);
        this.setCoverImgUrl(this.form.coverImgUrl);
      }
    },
    getCategoryNameById(categoryId,categoryList){
      if(categoryList == null){
        return "";
      }
      for(let i = 0; i < categoryList.length; i++){
        if(categoryList[i].categoryId == categoryId){
          return categoryList[i].text;
        }
        if(categoryList[i].children != [] && categoryList[i].children != null){
          if(this.getCategoryNameById(categoryId,categoryList[i].children) != ""){
            return this.getCategoryNameById(categoryId,categoryList[i].children);
          }
        }
      }
      return "";
    }
  }
};
</script>
